<template>
  <div class="form-container">
    <div class="data-container">
      <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
        <h3>订单客户信息</h3>
        <el-form-item label="客户名称" prop="customerId">
          <el-input v-model="addForm.customerId" placeholder="请输入客户名称" style="width: 200px"></el-input>
        </el-form-item>

        <h3>订单数据</h3>
        <el-form-item label="订单编号" prop="orderSn">
          <span>{{ addForm.orderSn }}</span>
        </el-form-item>
        <el-form-item label="发货仓库" prop="stash">
          <el-input v-model="addForm.stash" style="width: 500px" placeholder="请输入发货仓">
          </el-input>
        </el-form-item>
        <div style="display: flex; align-items: center;">
          <h3>产品信息</h3>
          <el-button @click="showProductDialog" type="primary" icon="el-icon-s-goods" plain style="margin-left: 20px">选择产品</el-button>
        </div>
        <el-table :data="productList" v-loading="listLoading" style="width: 100%;" :border="true">
          <el-table-column prop="productName" label="产品名称" width="100" :align="'center'"></el-table-column>
          <el-table-column prop="picture" label="产品图片" class="image-container-box"  :align="'center'">
            <template slot-scope="scope">
              <img :src="scope.row.picture" :preview-src-list="[scope.row.picture]" alt="Product Image"
                   style="width: 100px; height: 100px;">
            </template>
          </el-table-column>
          <el-table-column prop="price" label="产品价格" width="100" :align="'center'"></el-table-column>
          <el-table-column prop="costPrice" label="成本价" width="100" :align="'center'"></el-table-column>
          <el-table-column prop="productStock.stock" label="库存" width="100" :align="'center'"></el-table-column>
          <el-table-column label="采购数量" width="150" :align="'center'">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.purchaseQuantity" size="mini" :min="0"  :controls="false"
                               @change="calculateOrderAmount(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="salePrice" label="成交价" width="150" :align="'center'">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.salePrice" size="mini" :min="0"  :controls="false"
                               @change="calculateOrderAmount(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="订单金额" width="100" :align="'center'">
            <template slot-scope="scope">
              {{ calculateOrderAmount(scope.row).toFixed(2)  }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template scope="scope">
              <el-button type="text" size="mini" @click="cancelshowData(scope.row.id, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px; text-align: left; font-weight: bold;">
          订单总金额: {{ totalOrderAmount.toFixed(2) }} 元
        </div>
        <div style="margin-top: 20px; text-align: left; font-weight: bold;">
          总采购数量: {{ purchaseNum }} 箱
        </div>
        <h3>物流信息</h3>
        <el-form-item label="快递公司" prop="logisticsCompanies">
          <el-input v-model="addForm.logisticsCompanies" style="width: 500px" placeholder="请输入快递公司">
          </el-input>
        </el-form-item>
        <el-form-item label="快递备注" prop="notes">
          <el-input v-model="addForm.remarks" type="textarea" :rows="3" style="width: 500px"
                    auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="订单备注" prop="notes">
          <el-input v-model="addForm.notes" type="textarea" :rows="3" style="width: 500px"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="发货方式" prop="logisticsMethods">
          <el-select v-model="addForm.logisticsMethods" placeholder="请选择">
            <el-option
                v-for="item in ShippingMethod"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <h3>收款信息</h3>
        <el-form-item   label="收款方式" prop="payType">
          <el-input v-model="addForm.payType" style="width: 300px" placeholder="请输入收款方式">
          </el-input>
        </el-form-item>
        <el-form-item label="收款凭证" prop="receipt">
          <el-upload
              class="upload-demo"
              name="file"
              :action="this.$uploadURL"
              :on-remove="handleFileRemove"
              :on-success="handleFileUpload"
              :on-exceed="handleFileExceed"
              :multiple="true"
              :limit="5"
              :file-list="fileList"
              accept=".jpg,.png,.gif"
              list-type="picture">
            <!--              :headers="{ Authorization: 'Bearer ' + localStorage.getItem('token') }">-->
            <el-button size="small" type="primary">点击上传</el-button>
            <!--            <div slot="tip" class="el-upload__tip">只能上传指定类型图片文件，且不超过500kb</div>-->
          </el-upload>
        </el-form-item>

        <el-form-item label="订单审核人">
          <el-select v-model="addForm.orderReviewerId" placeholder="请选择">
            <el-option label="林阳阳" :value="377"></el-option>
            <el-option label="侯冬军" :value="380"></el-option>
            <el-option label="李曼曼" :value="379"></el-option>
            <el-option label="屈梦园" :value="390"></el-option>
            <el-option label="毛金雨" :value="387"></el-option>
            <el-option label="吴梦"  :value="389"></el-option>
          </el-select>
        </el-form-item>
          <h3>收件信息</h3>
        <el-row :gutter="24">
          <el-col :span="8">
          <el-form-item   label="收件人姓名"  prop="orderDetail.name" >
            <el-input v-model="addForm.orderDetail.name" placeholder="请输入收件人姓名">收件人姓名</el-input>
          </el-form-item>
          </el-col>
          <el-col :span="8">
          <el-form-item  label="收件人电话"  prop="orderDetail.phone">
            <el-input v-model="addForm.orderDetail.phone" placeholder="请输入收件人电话"></el-input>
          </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
          <el-form-item  label="收件省份" >
            <el-input v-model="addForm.orderDetail.province" placeholder="请输入收货省份"></el-input>
          </el-form-item>
          </el-col>
          <el-col :span="8">
          <el-form-item  label="收件市" >
            <el-input v-model="addForm.orderDetail.city" placeholder="请输入收货市"></el-input>
          </el-form-item>
          </el-col>
          <el-col :span="8">
          <el-form-item  label="收件区">
            <el-input v-model="addForm.orderDetail.district" placeholder="请输入收货区"></el-input>
          </el-form-item>
          </el-col>
        </el-row>
          <el-form-item  label="详细地址" prop="orderDetail.detailAddress">
            <el-input v-model="addForm.orderDetail.detailAddress" type="textarea" :rows="2" style="width: 500px"
                      auto-complete="off"></el-input>
          </el-form-item>

        </el-form>

      <div slot="footer" class="dialog-footer">

        <el-button v-perm="'orderList/addorder'" type="primary" @click.native="addSubmit" :loading="addLoading">创建订单</el-button>
      </div>
    </div>

    <el-dialog title="产品数据" :visible.sync="productFormVisible" :close-on-click-modal="false">
      <el-col :span="20" class="toolbar" style="padding-bottom: 5px;">
        <el-form :inline="true">
          <el-form-item style="display: flex; align-items: center;">
            <el-input v-model="keyword" placeholder="请输入产品名称" style="width: 230px"></el-input>
            <el-form-item>
              <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
            </el-form-item>
            <el-button type="success" @click="uptoorder">上传订单</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-table :data="productLists" highlight-current-row v-loading="listLoading"
                @selection-change="selsChange" style="width: 100%;" :border="true">
        <el-table-column align="center" type="selection" width="30"></el-table-column>
        <el-table-column align="center" prop="productName" label="产品名称" width="100" sortable></el-table-column>
        <el-table-column align="center" prop="picture" label="产品图片" width="100" :header-align="'center'"
                         :align="'center'">
          <template slot-scope="{row}">
            <el-image :src="row.picture"></el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="productClassify.productClassifyName" label="所属分类" width="140" sortable>
        </el-table-column>
        <el-table-column align="center" prop="productStock.stock" label="库存量" width="105" sortable>
        </el-table-column>
        <el-table-column align="center" prop="price" label="产品价格" width="110" sortable>
        </el-table-column>
        <el-table-column align="center" prop="label" label="标签" width="180">
          <template slot-scope="scope">
            <div class="tag-container">
      <span v-for="(tag, index) in scope.row.label" :key="index" class="tag-label">
        {{ tag }}
      </span>
            </div>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>

  </div>

</template>
<script>
import util from '../../common/js/util'

export default {
  data() {
    return {
      totalOrderAmount: 0.00, // 用于存储订单总金额
      purchaseNum:0,
      orderDetails: [], // 订单详情数组，包含产品ID、金额和数量
      sels: '',
      fileList: [],
      productFormVisible: false,//产品页面
      listLoading: false,
      productLists: [],
      productList: [],
      purchaseQuantity: '',
      selectedProductSet: new Set(),
      addLoading: false,
      addFormRules: {
        customerId:[{
          required: true, message: '请输入客户名称', trigger: 'blur'
        }],
        logisticsCompanies:[{
          required: true, message: '请输入快递公司', trigger: 'blur'
        }],
        logisticsMethods:[{
          required: true, message: '请输入发货方式', trigger: 'blur'
        }],
        orderReviewerId:[{
          required: true, message: '请输入订单审核人', trigger: 'blur'
        }],
        payType:[{
          required: true, message: '请输入收款方式', trigger: 'blur'
        }],
        'orderDetail.name':[{
          required: true, message: '请输入收件人姓名', trigger: 'blur'
        }],
        'orderDetail.phone'  :[{
          required: true, message: '请输入收件人电话', trigger: 'blur'
        }],
        'orderDetail.detailAddress' :[{
          required: true, message: '请输入收获详细地址', trigger: 'blur'
        }],
      },


      //新增界面数据
      addForm: {
        customerId: '',
        orderSn: '',
        stash: '',
        logisticsCompanies: '',
        notes: '',
        logisticsMethods: '',
        productId: '',
        payType: '',
        receipt: [],
        loginId: '',
        remarks:'',//快递备注
        productNumber: '',
        orderAmount: '',
        orderProducids:[],
        orderDetail: {
          id: '',
          name: '',
          phone: '',
          province: '',
          city: '',
          district: '',
          detailAddress: '',
        },
        orderReviewerId:'',
      },
      //发货方式的选择
      ShippingMethod: [
        {label:"快递",value:"快递"},{label:"物流",value:"物流"},{label:"自提",value:"自提"},
        {label:"自己叫车",value:"自己叫车"},{label:"整车拉",value:"整车拉"},
      ],
      //订单审核人
      orderReviewer:{
        id:'',
        adminName: '',
      },
      customerLists: [],
      serousList: [],
      total: 0,
      currentPage: 1,
      keyword: '',
      totals: 0,
      pageSize: 500,
    }
  },
  created() {
    // 在组件创建时生成订单编号并设置为默认值
    this.addForm.orderSn = this.generateOrderSn();
  },
  methods: {
    generateOrderSn() {
      // 生成订单编号的逻辑，这里使用当前时间的简单示例
      const currentTime = new Date();
      const year = currentTime.getFullYear();
      const month = (currentTime.getMonth() + 1).toString().padStart(2, '0');
      const day = currentTime.getDate().toString().padStart(2, '0');
      const hour = currentTime.getHours().toString().padStart(2, '0');
      const minute = currentTime.getMinutes().toString().padStart(2, '0');
      const second = currentTime.getSeconds().toString().padStart(2, '0');

      return `${year}${month}${day}${hour}${minute}${second}`;
    },
    calculateOrderAmount(product) {
      // 找到订单详情中是否已经存在该产品
      const orderDetail = this.orderDetails.find(detail => detail.id === product.id);
      let amount = (product.salePrice * product.purchaseQuantity).toFixed(2);

      if (orderDetail) {
        // 更新已存在的订单详情
        orderDetail.amount = parseFloat(amount);
        orderDetail.quantity = product.purchaseQuantity;
        orderDetail.salePrice = product.salePrice;
      } else {
        // 新增订单详情
        this.orderDetails.push({
          id: product.id,
          amount: parseFloat(amount),
          quantity: product.purchaseQuantity,
          salePrice: product.salePrice
        });
      }

      // 统计所有产品的选购数量
      this.purchaseNum = this.orderDetails.reduce((total, detail) => {
        return total + detail.quantity;
      }, 0);

      // 重新计算总金额
      this.totalOrderAmount = this.orderDetails.reduce((total, detail) => {
        return total + detail.amount;
      }, 0);

      return orderDetail ? orderDetail.amount : 0;
    },

    renderOptionLabel(customer) {
      return `${customer.customerName} - ${customer.phoneNumber}`;
    },
    showProductDialog: function () {
        this.productFormVisible = true;
        this.getproductLists();
    },
    getcustomerLists() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize = 500,
        keyword: this.keyword,
      };
      this.listLoading = true;
      this.$http.post("/customMycustom", para).then((res) => {
        this.customerLists = res.data.records;
        this.totals = res.data.total;
        this.currentPage = para.currentPage; // 更新当前页数
      }).catch(res => {
        this.$message.warning("系统繁忙，请稍后重试!!!")
      });
    },

//获取归属人
    getOrderReviewer() {
      this.$http.get("/employee").then(res => {
        this.orderReviewer = res.data;
      });
    },
    keywordQuery() {
      //查询完，原来分页条件已经没用了，要跑到第一页去
      this.currentPage = 1;
      this.getproductLists();
    },

//获取产品数据
    getproductLists() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword,
      };
      this.listLoading = true;
      this.$http.post("/productList/forSale", para).then((res) => {
        this.totals = res.data.total;
        // 处理每个产品的标签，将空格分隔的字符串转换为数组
        this.productLists = res.data.records.map(product => {
          return {
            ...product,
            label: product.label ? product.label.split(' ') : [] // 将空格分隔的字符串转换为数组
          };
        });
        this.listLoading = false;
      }).catch(res => {
        this.$message.warning("系统繁忙，请稍后重试!!!")
      });
    },

    //上传到订单
    uptoorder: function () {
      if (this.selectedProductSet.size >= 1) {
        // 获取选中的产品ID
        const uploadedProductId = Array.from(this.selectedProductSet);
        // 在productLists中找到选中的产品并添加到productList和orderDetails中
        uploadedProductId.forEach((uploadedProductId) => {
          const selectedProduct = this.productLists.find(product => product.id === uploadedProductId);
          if (!this.productList.some(product => product.id === selectedProduct.id)) {
            // 将选中的产品添加到productList中
            this.productList.push(selectedProduct);
            // 将选中的产品ID添加到orderDetails中
            this.orderDetails.push({
              id: selectedProduct.id,
              amount: 0,
              quantity: 0,
              salePrice:0,
            });
          }
        })

        // 清除selectedProductSet
        this.selectedProductSet.clear();
        // 关闭对话框
        this.productFormVisible = false;
      } else {
        // 提示用户只能选择一个产品
        this.$message.warning('请选择一个产品进行上传');
      }
    },


      cancelshowData(productId, row) {
        // 在 productList 中找到与当前 productId 相匹配的产品，并删除
        const index = this.productList.findIndex(product => product.id === productId);
        if (index !== -1) {
          this.productList.splice(index, 1);
        }

        // 删除 orderDetails 中具有相同产品 ID 的整个数据对象
        this.orderDetails = this.orderDetails.filter(detail => detail.id !== productId);
        // 重新计算总金额
        // 统计所有产品的选购数量
        this.purchaseNum = this.orderDetails.reduce((total, detail) => {
          return total + detail.quantity;
        }, 0);

        this.totalOrderAmount = this.orderDetails.reduce((total, detail) => {
          return total + detail.amount;
        }, 0);
      },
    //文件删除时的回调
    handleFileRemove(file, fileList) {
      //正式删除
      var fileName = null;
      if (file.response) {  //上传图片的时候点了删除
        fileName = file.response.resultObj;
      } else {  //点击修改回显的图片，点了删除
        fileName = file.url;
      }
      //为了方便参数传递,需要转换路径写法,把/替换为_
      fileName = fileName.replaceAll("/", "_");
      //发送请求
      this.$http.delete("/minio/" + fileName).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
          this.fileList = [];
          this.addForm.picture = "";
        } else {
          this.$message.error("删除失败");
        }
      })
    },

    //文件上传成功之后的回调
    handleFileUpload(response) {
      if (response.success) {
        this.addForm.receipt.push(response.resultObj);
      }
    },
    //上传超过数量的回调
    handleFileExceed() {
      this.$message.error("不能上传多张图片");
    },

    //6.选项改变时触发
    selsChange: function (sels) {
      this.selectedProductSet = new Set(sels.map(item => item.id));
    },
    //11.新增
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('检测到客户信息不属于系统，需要创建客户信息！确定添加吗？', '提示', {}).then(() => {
            this.addLoading = true;
            const logininfo = JSON.parse(localStorage.getItem("logininfo"));
            this.addForm.loginId = logininfo.id;
            const orderProductIdList = this.orderDetails.reduce((result, detail) => {
              result.push({
                productId: detail.id,
                orderAmount: detail.amount,
                orderNum: detail.quantity,
                salePrice:detail.salePrice,
              });
              return result;
            }, []);
            this.addForm.orderProducids = orderProductIdList;
            let para = Object.assign({}, this.addForm);
            para.receipt=para.receipt.join(',');
            //先新增加客户信息
            // 跳转到添加客户信息的页面，同时传递当前订单页面的数据
            this.$router.push({
              name: '创建订单',
              params: {
                orderData: para
              }
            });
          });
        }
      });
    },
  },
  mounted() {
    this.getcustomerLists();
    this.getOrderReviewer();
  }
}

</script>
<style>
.form-container {
  margin-top: 50px;
  margin-left: 10px;
  width: 1000px;
  height: 800px;
}
</style>
<style scoped>
.tag-container {
  display: flex;
  align-items: center; /* 让标签垂直居中显示 */
  flex-wrap: wrap;
}

.tag-label {
  background-color: #e6f1fe;
  color: #1d8ce0;
  padding: 4px 8px;
  border-radius: 4px;
  margin-right: 8px; /* 间隔大小可以根据需要调整 */
  margin-bottom: 3px;
  white-space: nowrap; /* 防止文字换行 */
  display: inline-block; /* 让每个标签作为一个块级元素显示 */
}


</style>